package PriceCalculator;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class PriceCalculator {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\si\\IdeaProjects\\10\\src\\PriceCalculator\\price.txt";
        List<Integer> prices = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String priceStr = line.substring(line.indexOf("元") - 4, line.indexOf("元"));
                prices.add(Integer.parseInt(priceStr));
                System.out.println("从文档中解析的数据为"+priceStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        double averagePrice = prices.stream().mapToInt(Integer::intValue).average().orElse(0.0);

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) {
            bw.newLine();
            bw.write("平均价格: " + averagePrice + "元");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("平均价格已计算并写入文件: " + averagePrice + "元");
    }
}